import Config from '../utils/config2'
import commonServ from './commonServ'
var regeneratorRuntime = require("../lib/js/runtime-module.js")
import cf from '../config'
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 获取地址参数
const getUrlParam = (name) => {
  // 获取参数
  let url = window.location.search
  // 正则筛选地址栏
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  // 匹配目标参数
  let result = url.substr(1).match(reg)
  //返回参数值
  return result ? decodeURIComponent(result[2]) : null
}
//取回cookie
const getCookieCache = (c_name) => {
  if (document.cookie.length > 0) {
    var c_start = document.cookie.indexOf(c_name + '=')
    if (c_start != -1) {
      c_start = c_start + c_name.length + 1
      var c_end = document.cookie.indexOf(';', c_start)
      if (c_end == -1) c_end = document.cookie.length
      return unescape(document.cookie.substring(c_start, c_end))
    }
  }
  return ''
}
//
const includes = (statusList, curStatus) => {
  return statusList.indexOf(Number(curStatus)) > -1
}
//较验登录
const flagLogin = () => {
  if (wx.getStorageSync(Config.authName).length > 0) {
    wx.navigateTo({
      url: '../pages/biz/login/login',
    })
  }
}

//防止多次跳转
const navigateStateChange = (self, disableKey) => {
  self.setData({
    [disableKey]: true
  })

  setTimeout(function () {
    self.setData({
      [disableKey]: false
    })
  }, 500)
}
//解决new Date（）在ios中为null
const dateFromString = (time = null) => {
  //console.log(time)
  if (time) {
    time = time.replace(/[-|.]/g, ":").replace(' ', ':')
    time = time.split(':')
    var time1 = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5])
    //console.log(time)
    return time1
  } else {
    return new Date()
  }
}
//转成中文日期
const dateChina = (time = null) => {
  //console.log(time)
  if (time) {
    time = time.replace(/[-|.]/g, ":").replace(' ', ':')
    time = time.split(':')
    //var time1 = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5])
    //console.log(time)
    return `${time[0]}年${time[1]}月${time[2]}日${time[3]}:${time[4]}`
  } else {
    return ''
  }
}
//时间转换
const formatDate = function (str, type = 1) {
  let [y, m, d, h, min, s] = str.replace(/[-|:]/g, " ").split(" ");
  let ns = "";
  switch (type) {
    case 1:
      ns = y + "." + m + "." + d
      break
    case 2:
      ns = y + "." + m + "." + d + " " + h + ":" + min + ":" + s
      break
  }
  return ns
}
//为Date原型添加时间格式化方法
Date.prototype.format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1,                 //月份
    'd+': this.getDate(),                    //日
    'h+': this.getHours(),                   //小时
    'm+': this.getMinutes(),                 //分
    's+': this.getSeconds(),                 //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    'S': this.getMilliseconds()             //毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

const priceFormat = function (s = 0, dot = ',') {
  if (isNaN(s)) {
    return s
  }
  s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(2) + ''
  var l = s.split('.')[0].split('').reverse(),
    r = s.split('.')[1]
  t = ''
  for (i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '')
  }
  return t.split('').reverse().join('') + '.' + r
}

//计时器类
class TimerClass {
  constructor(totalCount = 60, cbk = null) {
    this.totalCount = Number(totalCount) + 1
    this.cbk = cbk
    this._reset({ totalCount, cbk })
  }

  _reset() {
    this.timer && clearTimeout(this.timer)
    this.timer = null
    this.disabled = false
    this.currentCount = this.totalCount
    this.countText = '获取验证码'
    this.cbk && this.cbk(this.currentCount, this.countText)
  }

  _clock() {
    if (this.currentCount > 0) {
      this.currentCount--
    } else {
      this.stop()
    }
    this.countText = this.disabled ? `重新获取（${this.currentCount}）s` : '获取验证码'
    this.cbk && this.cbk(this.currentCount, this.countText)
  }

  start() {
    var that = this;
    if (this.disabled) {
      return false
    }
    this.disabled = true
    this.cbk && this.cbk(this.currentCount, this.countText)
    clearTimeout(this.timer)
    function countClock() {
      that._clock();
      that.timer = setTimeout(countClock, 1000)
    }
    countClock();
  }

  stop() {
    this._reset()
  }
}
//身份证隐藏
const formatIdcard = function (idcard) {
  if (idcard.length == 15) {
    return idcard.replace(/(\d{4})\d{8}(\d{3})/, "$1********$2");
  } else {
    return idcard.replace(/(\d{4})\d{8}(\d{3})/, "$1********$2");
  }
}
//手机验证
const formatPhone = function () {

}
//手机验证
const hidePhone = function (tel) {
  var reg = /^(\d{3})\d{4}(\d{4})$/;
  tel = tel.replace(reg, "$1****$2");
  return tel
}
const timeFormat = function (param) { //小于10的格式化函数
  return param < 10 ? '0' + param : param;
}
//结束时间与当前时间对比
const contrastDate = function (endDate) {
  let date = dateFromString(endDate);
  date = date.getTime();
  let date1 = dateFromString()
  date1 = date1.getTime();
  if (date > date1) {
    //未过期
    return true
  } else {
    //已过期
    return false
  }
}
/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/
const formatTimestamp = function (number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
//还有多少天
const dayTo = function (time,nowTime) {
  let newTime = nowTime?nowTime:new Date().getTime();
  // 对结束时间进行处理渲染到页面
  let endTime = nowTime?time:dateFromString(time).getTime();
  let obj = null;
  // 如果活动未结束，对时间进行处理
  if (endTime - newTime > 0) {
    let time = (endTime - newTime) / 1000;
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    return obj = {
      day: day,
      hou: hou,
      min: min,
      sec: sec
    }
  } else { //活动已结束，全部设置为'00'
    return obj = {
      day: '00',
      hou: '00',
      min: '00',
      sec: '00'
    }
    //竞拍倒计时结束节点
    // wx.startPullDownRefresh()
    // clearTimeout(this.data.timerAu)

  }

}

//生产uuid
const generateUUID = function () {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}

const clearStorage = function (retainKey) {
  if (retainKey) {
    let retainMap = {}
    //暂存需要保留的键值
    retainKey.forEach(function (v, k) {
      retainMap[v] = wx.getStorageSync(v)
    });
    wx.clearStorageSync();
    for (var key in retainMap) {
      wx.setStorageSync(key, retainMap[key])
    }
  } else {
    wx.clearStorageSync();
  }
}
const clearStorageKey = function (removeKey) {
  removeKey.forEach(function (v, k) {
    try {
      wx.removeStorageSync(key)
    } catch (e) {
    }
  });
}
const bgPromise = function (item) {
  let bgPromiseVar = new Promise(function (resolve, reject) {
    wx.getImageInfo({
      src: item,
      success: function (res) {
        resolve(res);
      }
    })
  });
  return bgPromiseVar
}
//图片预加载
const imgPreLoad = function (imgArr, cbk) {
  let promiseList = []
  let preLoadImg = []
  imgArr.length > 0 && imgArr.map((item, idx) => {
    promiseList.push(bgPromise(item))
  })
  Promise.all(promiseList).then((res) => {
    res.map((item, idx) => {
      preLoadImg.push(item.path)
    })
    cbk && cbk(preLoadImg)
  })
}
const getWxacode = async function (sendData, pageName, type) {
  let userId = wx.getStorageSync(Config.userIdKey)
  let recommendPhone = wx.getStorageSync(Config.phoneNoKey)
  console.log(userId)
  let basePage = type == 1 ? '/pages/' : '/subPackages/pages /'
  pageName = pageName == '' ? 'index' : pageName
  let params = {
    // page: `pages/wxcodeTransferStation/wxcodeTransferStation`, //小程序码中间跳转页面
    page: `pages/wxcodeTransferStation/wxcodeTransferStation`,
    // page: `pages/biz/index/index`,//小程序码中间跳转页面
    targetPage: basePage + pageName + '/' + pageName,
    userId,
    //是否透明化处理，1：处理，非1或空不处理
    //type 0:美房详情 1:我的分享
    isTransparent: 0,
    recommendPhone,
    recommendType: type,
    channel: '1010'
  }
  params = Object.assign(params, sendData)
  let { success, data } = await commonServ.wxacodeGet(params)
  if (success) {
    //console.log(data)
    return data
  }
}

//省市区截取
let area = function(str) {
  let area = {}
  let index11 = 0
  let index1 = str.indexOf("省")
  if (index1 == -1) {
    index11 = str.indexOf("自治区")
    if (index11 != -1) {
      area.province = str.substring(0, index11 + 3)
    } else {
      area.province = str.substring(0, 0)
    }
  } else {
    area.province = str.substring(0, index1 + 1)
  }

  let index2 = str.indexOf("市")
  if (index11 == -1) {
    area.city = str.substring(index11 + 1, index2 + 1)
  } else {
    if (index11 == 0) {
      area.city = str.substring(index1 + 1, index2 + 1)
    } else {
      area.city = str.substring(index11 + 3, index2 + 1)
    }
  }

  let index3 = str.lastIndexOf("区")
  if (index3 == -1) {
    index3 = str.indexOf("县")
    area.country = str.substring(index2 + 1, index3 + 1)
  } else {
    area.country = str.substring(index2 + 1, index3 + 1)
  }
  return area;
}

module.exports = {
  formatTime,
  includes,
  getWxacode,
  navigateStateChange,
  dateFromString,
  priceFormat,
  TimerClass,
  flagLogin,
  formatIdcard,
  hidePhone,
  dayTo,
  formatDate,
  contrastDate,
  dateChina,
  formatTimestamp,
  generateUUID,
  clearStorage,
  clearStorageKey,
  imgPreLoad,
  area
}
